package main

import "fmt"

func Slice() {
	s1 := []int{1, 2, 3, 4}
	fmt.Printf("s1: %v, len:%d, cap:%d \n", s1, len(s1), cap(s1))

	//创建长度为3，容量为4的切片
	s2 := make([]int, 3, 4)
	fmt.Printf("s2: %v, len:%d, cap:%d \n", s2, len(s2), cap(s2))

	s2 = append(s2, 7) //打印：s2: [0 0 0 7], len:4, cap:4
	fmt.Printf("s2: %v, len:%d, cap:%d \n", s2, len(s2), cap(s2))

	//扩容了，原本cap容量都是4，现在变成8了
	s2 = append(s2, 8) //打印：s2: [0 0 0 7 8], len:5, cap:8
	fmt.Printf("s2: %v, len:%d, cap:%d \n", s2, len(s2), cap(s2))

	s3 := make([]int, 4) //容量和长度都是4
	fmt.Printf("s3: %v, len:%d, cap:%d \n", s3, len(s3), cap(s3))

	//按下标索引
	fmt.Printf("s3[2] : %d", s3[2])
	//超出下标范围返回 panic
	//fmt.Printf("s3[99] : %d", s3[99])
}

// 子切片
func Subslice() {
	s1 := []int{2, 4, 6, 8, 10}
	s2 := s1[1:3] //打印：s2: [4 6], len:2, cap:4
	fmt.Printf("s2: %v, len:%d, cap:%d \n", s2, len(s2), cap(s2))

	s3 := s1[1:] //打印：s3: [4 6 8 10], len:4, cap:4
	fmt.Printf("s3: %v, len:%d, cap:%d \n", s3, len(s3), cap(s3))

	s4 := s1[:3] //打印：s4: [2 4 6], len:3, cap:5
	fmt.Printf("s4: %v, len:%d, cap:%d \n", s4, len(s4), cap(s4))
}

func ShareSlice() {
	//切片与子切片共享数组
	s1 := []int{1, 2, 3, 4}
	s2 := s1[2:]
	fmt.Printf("s1: %v, len:%d, cap:%d \n", s1, len(s1), cap(s1))
	fmt.Printf("s2: %v, len:%d, cap:%d \n \n", s2, len(s2), cap(s2))

	s2[0] = 99
	fmt.Printf("s1: %v, len:%d, cap:%d \n", s1, len(s1), cap(s1))
	fmt.Printf("s2: %v, len:%d, cap:%d \n \n", s2, len(s2), cap(s2))

	s2 = append(s2, 199) //原因在于在这里扩容了，所以不会和共享原数组
	fmt.Printf("s1: %v, len:%d, cap:%d \n", s1, len(s1), cap(s1))
	fmt.Printf("s2: %v, len:%d, cap:%d \n \n", s2, len(s2), cap(s2))

	s2[1] = 888
	fmt.Printf("s1: %v, len:%d, cap:%d \n", s1, len(s1), cap(s1))
	fmt.Printf("s2: %v, len:%d, cap:%d \n \n", s2, len(s2), cap(s2))
}
